using System.Text;
using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using Microsoft.Extensions.Configuration;

namespace Wechat.Service.Filter;

public class FilterService : IFilterService
{
    public FilterService() { }

    public async Task<string> FilterByArticlePathAsync(string path)
    {
        // 使用StreamReader读取文件
        using StreamReader reader = new StreamReader(path, Encoding.UTF8); // 这里假设文件编码为UTF8

        // 读取文件全部内容
        string htmlContent = reader.ReadToEnd();
        var startFlag = false;
        var endFlag = false;

        // 解析HTML内容
        var document = await new HtmlParser().ParseDocumentAsync(htmlContent);
        IElement? element = document.QuerySelector("#js_content");
        element?.SetAttribute("style", "");

        // start --------------------------------------
        IHtmlCollection<IElement> pElements = document.QuerySelectorAll("p");
        foreach (IElement pElement in pElements)
        {
            if (startFlag)
                break;
            // <section style="box-sizing: border-box;width: 100%;height: 14px;background: rgb(198, 227, 227);margin-top: -10px;overflow: hidden;text-align: justify;" data-width="100%"><br></section>

            //
            if (
                pElement.InnerHtml
                == "<span style=\"line-height: 150%;font-family: 宋体;font-size: 18px;\">(接前文)</span>"
            )
            {
                pElement.TextContent = "-----start-----";
                startFlag = true;
                break;
            }
            if (pElement.InnerHtml.Contains("(接前文)"))
            {
                pElement.TextContent = "-----start-----";
                startFlag = true;
                break;
            }
            if (pElement.InnerHtml.Contains("接前文"))
            {
                pElement.TextContent = "-----start-----";
                startFlag = true;
                break;
            }
            // <span style="font-family: 宋体;font-size: 16px;color: rgb(0, 0, 0);">附录</span>
            if (
                pElement.InnerHtml
                == "<span style=\"font-family: 宋体;font-size: 16px;color: rgb(0, 0, 0);\">附录</span>"
            )
            {
                pElement.TextContent = "-----start-----";
                startFlag = true;
                break;
            }
            if (pElement.InnerHtml.Contains("思维导图"))
            {
                pElement.TextContent = "-----start-----";
                startFlag = true;
                break;
            }
        }

        // end---------------------------------------------------------------
        // <span style="font-size: 14px;color: rgb(136, 136, 136);">（未完待续)</span>
        IHtmlCollection<IElement> endPElements = document.QuerySelectorAll("p");
        foreach (IElement pElement in endPElements)
        {
            if (endFlag)
                break;
            if (
                pElement.InnerHtml
                == "<span style=\"font-size: 14px;color: rgb(136, 136, 136);\">（未完待续)</span>"
            )
            {
                pElement.TextContent = "-----end-----";
                endFlag = true;
                break;
            }

            if (
                pElement.InnerHtml
                == "<span style=\"color: rgb(136, 136, 136);font-size: 14px;text-align: right;\">（未完待续)</span><br>"
            )
            {
                pElement.TextContent = "-----end-----";
                endFlag = true;
                break;
            }
            if (pElement.InnerHtml.Contains("未完待续"))
            {
                pElement.TextContent = "-----end-----";
                endFlag = true;
                break;
            }
            //
        }
        IHtmlCollection<IElement> endStrongElements = document.QuerySelectorAll("strong");
        foreach (IElement pElement in endStrongElements)
        {
            if (pElement.InnerHtml.Contains("往期链接"))
            {
                pElement.TextContent = "-----end-----";
                endFlag = true;
                break;
            }
        }

        // middle --------------------
        // var spanElements = document.QuerySelectorAll("span");
        // foreach (var span in spanElements)
        // {
        //     // 检查<span>元素的style属性
        //     var style = span.GetAttribute("style");
        //     if (
        //         style != null
        //         && style.Contains("max-width: 100%;")
        //         && style.Contains("line-height: 24px;")
        //         && style.Contains("font-family: 宋体;")
        //         && style.Contains("color: rgb(136, 136, 136);")
        //     )
        //     {
        //         // if (span.TextContent.Contains("伟大的菩萨来到世间利益众生"))
        //         // {
        //         //     bodyHtml = bodyHtml.Replace(span.OuterHtml, "");
        //         // }
        //     }
        // }

        var bodyHtml = document.QuerySelector("#js_content")?.OuterHtml!;
        var body = @$"<!DOCTYPE html><html><head></head><body>{bodyHtml}</body></html>";
        return body;
    }

    public string FormatContent(string content)
    {
        return content.Replace("。", "。\n\n");
    }

    public string ReplaceHtmlHref(string html)
    {
        return html.Replace(@"href=""//res.wx.qq.com", @"href=""https://res.wx.qq.com")
            .Replace(@"href=""//mmbiz.qpic.cn", @"href=""https://mmbiz.qpic.cn")
            .Replace(@"href=""//mpcdn.qpic.cn", @"href=""https://mpcdn.qpic.cn")
            .Replace(@"href=""//mpcdn.weixin.qq.com", @"href=""https://mpcdn.weixin.qq.com")
            .Replace(@"href=""//wxa.wxs.qq.com", @"href=""https://wxa.wxs.qq.com")
            .Replace(@"href=""//file.daihuo.qq.com", @"href=""https://file.daihuo.qq.com")
            .Replace(@"src=""//res.wx.qq.com", @"src=""https://res.wx.qq.com")
            .Replace(@"data-src=""//res.wx.qq.com", @"data-src=""https://res.wx.qq.com")
            .Replace(@"location.protocol", @"https:");
    }

    public async Task<string> DeleteScrpitsAsync(string html)
    {
        var document = await new HtmlParser().ParseDocumentAsync(html);
        IHtmlCollection<IElement> pElements = document.QuerySelectorAll("script");
        foreach (IElement pElement in pElements)
        {
            pElement.ParentElement?.RemoveChild(pElement);
        }

        document.QuerySelector("#js_content")?.SetAttribute("style", "visibility: visible;");

        var bodyHtml = document.QuerySelector("html")?.OuterHtml!;
        return bodyHtml;
    }

    public async Task<bool> HasJsContent(string html)
    {
        var document = await new HtmlParser().ParseDocumentAsync(html);
        IElement? jsContentEle = document.QuerySelector("#js_content");
        if (jsContentEle == null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    public static string SanitizeFileName(string fileName)
    {
        string invalidChars = System.Text.RegularExpressions.Regex.Escape(
            new string(System.IO.Path.GetInvalidFileNameChars())
        );
        string invalidRegStr = string.Format(@"([{0}]*\.+$)|([{0}]+)", invalidChars);

        return System.Text.RegularExpressions.Regex.Replace(fileName, invalidRegStr, "_");
    }

    public async Task<string> GetArticleTitle(string html)
    {
        var document = await new HtmlParser().ParseDocumentAsync(html);
        IElement? titleEle = document.QuerySelector("#activity-name");

        if (titleEle == null)
        {
            return string.Empty;
        }
        else
        {
            return SanitizeFileName(titleEle.TextContent.Trim());
        }
    }

    public async Task<bool> GetOrignalStatus(string html)
    {
        if (html.Split(@"_copyright_stat = """).Last().Substring(0, 1) == "0")
        {
            return false;
        }
        else
        {
            return true;
        }
    }


}
